layui.define(['layer', 'tree', 'form', 'validation', 'treeSelect', 'element', 'selectPlus', 'laydate'], function (exports) {
    "use strict";
    const $ = layui.jquery,
        form = layui.form,
        validation = layui.validation,
        selectPlus = layui.selectPlus,
        laydate = layui.laydate,
        treeSelect = layui.treeSelect,
        element = layui.element,
        tree = layui.tree;
    let dynamicform = {
        init: function ({btn}) {
            let html = dynamicform.element(btn);
            return html;
        },
        submit: function (filter, {formparam, lables, row}, task) {
            form.on('submit(' + filter + ')', function (data) {
                formparam.type = $(data.elem).attr("data-subtype");
                let rowdata = $(data.elem).attr("data-val");
                if ("update,insert,delete".indexOf(formparam.type) == -1) {
                    if (task) task(formparam, JSON.parse(rowdata))
                    return;
                }
                dynamicform.openwind(formparam, lables, rowdata, task);
            });
        },
        onsubmit: function (filter, {formparam, lables, row}, task) {
            for (let i in filter) {
                $("." + filter[i]).on("click", function () {
                    formparam.type = $(this).attr("data-subtype");
                    let rowdata = $(this).attr("data-val");
                    if ("update,insert,delete".indexOf(formparam.type) == -1) {
                        if (task) task(formparam, JSON.parse(rowdata))
                        return;
                    }
                    dynamicform.openwind(formparam, lables, rowdata, task);
                })
            }
        },
        element: function (lables) {
            let html = "";
            for (let i in lables) {
                let lable = lables[i];
                if (lable.type == "button") {
                    let temp = "";
                    for (let key in lable.events) {
                        temp += " " + key + "=\"" + lable.events[key] + "\"";
                    }
                    html += "<a lay-submit class=\"layui-btn " + lable.class + "\" name=\"" + lable.name + "\" lay-filter=\"" + lable.filter + "\" data-subtype=\"" + lable.subtype + "\" lay-event=\"" + lable.event + "\" " + temp + " data-val=\"" + lable.data + "\">" + lable.title + "</a>";
                }
            }
            return html;
        },
        render: function (formparam, lables) {
            function appendHtml(title, tempHtml) {
                let temp = "<div class=\"layui-form-item\">";
                temp += "<label class=\"layui-form-label\">" + title + "</label>";
                temp += "<div class=\"layui-input-block\">" + tempHtml + "</div>";
                temp += "</div>";
                return temp;
            }

            let formstyle = "";
            for (let key in formparam.style) {
                formstyle += key + ":" + formparam.style[key] + ";";
            }
            let html = "<div class=\"layui-form\">";
            html += "<form class=\"layui-form\" lay-filter=\"" + formparam.filter + "-example\" style=\"padding: 20px 20px 0 0;" + formstyle + "\">";
            for (let i in lables) {
                /**
                 form：{
                     type:""+subtype+"",//表单提交类型
                     style:{
                         overflow:"hidden"
                     },//自定义样式
                     filter:"layer_map_form"//唯一标识
                 };
                 **/
                let lable = lables[i];
                let tempHtml = "";
                /** {title:"",type:"",name:"",verify:"",placeholder:"",value:"",disabled:""} */
                if (lable.type == 'hidden') {
                    tempHtml = "<input type=\"hidden\" name=\"" + lable.name + "\" value=\"" + lable.value + "\" autocomplete=\"off\" placeholder=\"" + lable.placeholder + "\" class=\"layui-input\" " + (lable.hasOwnProperty("verify") ? "lay-verify=\"" + lable.verify + "\"" : "") + " " + (lable.hasOwnProperty("disabled") ? "disabled" : "") + ">";
                }
                /** {title:"",type:"",name:"",verify:"",placeholder:"",value:"",disabled:""} */
                if (lable.type == 'text') {
                    tempHtml = "<input type=\"text\" name=\"" + lable.name + "\" lay-verify=\"" + lable.verify + "\" autocomplete=\"off\" placeholder=\"" + lable.placeholder + "\" class=\"layui-input\" " + (lable.hasOwnProperty("verify") ? "lay-verify=\"" + lable.verify + "\"" : "") + " " + (lable.hasOwnProperty("disabled") ? "disabled" : "") + ">";
                }
                /** 时间选择器：{title:"xxx",type:"date",placeholder:"",} **/
                if (lable.type == 'date') {
                    tempHtml = `<input type="text" name="${lable.name}" id="${lable.name}" lay-verify="date" placeholder="${lable.placeholder}" autoComplete="off" class="layui-input">`
                }
                /** 下拉多选组件（非树）{title: "xx",type:"checkgroup",data:[{name: 'xx', title: 'xx', id: x},{...}]} **/
                if (lable.type == 'checkgroup') {
                    tempHtml = ` <div id="${lable.name}" lay-filter="${lable.name}" class="layui-input" style="padding: 0 !important;"></div>`
                }
                /** 下拉多选人员/单选单位树组件 {title:"xx",type:"treeuser/treedanwei",name:"xx",} **/
                if (lable.type == 'selecttree') {
                    tempHtml = `<div class="layui-unselect layui-form-select ${lable.name}">`;
                    tempHtml += `<div class="layui-select-title">`;
                    tempHtml += `<span class="layui-input layui-unselect">${lable.placeholder}</span>`;
                    tempHtml += `<input type="hidden" name="${lable.name}">`;
                    tempHtml += `<i class="layui-edge"></i>`;
                    tempHtml += `</div>`;
                    tempHtml += `<dl class="layui-anim layui-anim-upbit">`;
                    tempHtml += `<dd>`;
                    tempHtml += `<ul id="${lable.name}-tree"></ul>`;
                    tempHtml += `</dd>`;
                    tempHtml += `</dl>`;
                    tempHtml += `</div>`
                }
                /** 下拉多选人员/单选单位树组件 {title:"xx",type:"treeuser/treedanwei",name:"xx",} **/
                if (lable.type == 'treeuser' || lable.type == 'treedanwei') {
                    tempHtml = `<input type="text" name="${lable.name}" id="${lable.name}" lay-filter="${lable.name}" class="layui-input">`
                }
                /** {title:"",type:"",title:"",data:[{width:"",name:"",filter:"",placeholder:"",verify:""}]} */
                if (lable.type == 'text-pro') {
                    tempHtml = "<div class=\"layui-form-item\">";
                    tempHtml += "<label class=\"layui-form-label\">" + lable.title + "</label>";
                    for (let o in lable.data) {
                        tempHtml += "<div class=\"layui-input-inline\" style=\"width: " + lable.data[o].width + "px;\">";
                        tempHtml += "<input type=\"text\" name=\"" + lable.data[o].name + "\"  lay-filter=\"" + lable.filter + "\" placeholder=\"" + lable.data[o].placeholder + "\" autocomplete=\"off\" class=\"layui-input\" " + (lable.data[o].hasOwnProperty("verify") ? "lay-verify=\"" + lable.data[o].verify + "\"" : "") + ">";
                        tempHtml += "</div>";
                    }
                    tempHtml += "</div>";
                }
                /** {title:"",type:"",name:"",filter:"",verify:"",search:"",placeholder:"",data:[{value:"",title:""}]} */
                if (lable.type == 'select') {
                    tempHtml = "<select name=\"" + lable.name + "\" lay-filter=\"" + lable.filter + "\" " + (lable.hasOwnProperty("verify") ? "lay-verify=\"" + lable.verify + "\"" : "") + " lay-search=\"" + lable.search + "\">";
                    tempHtml += "<option value=\"\">" + lable.placeholder + "</option>";
                    for (let o in lable.data) {
                        tempHtml += "<option value=\"" + lable.data[o].value + "\">" + lable.data[o].title + "</option>";
                    }
                    tempHtml += "</select>";
                }
                /** {title:"",type:"",data:[{name:"",filter:"",value:"",title:"",checked:"",disabled:""}]} */
                if (lable.type == 'radio') {
                    for (let o in lable.data) {
                        tempHtml += "<input type=\"radio\" name=\"" + lable.data[o].name + "\" lay-filter=\"" + lable.data[o].filter + "\" value=\"" + lable.data[o].value + "\" title=\"" + lable.data[o].title + "\" " + (lable.data[o].hasOwnProperty("checked") ? "checked" : "") + " " + (lable.data[o].hasOwnProperty("disabled") ? "disabled" : "") + ">";
                    }
                }
                /** {title:"",type:"",data:[{name:"",filter:"",title:"",checked:"",disabled:""}]} */
                if (lable.type == 'checkbox') {
                    for (let o in lable.data) {
                        tempHtml += "<input type=\"checkbox\" name=\"" + lable.data[o].name + "\" lay-skin=\"primary\" lay-filter=\"" + lable.data[o].filter + "\" title=\"" + lable.data[o].title + "\" " + (lable.data[o].hasOwnProperty("checked") ? "checked" : "") + " " + (lable.data[o].hasOwnProperty("disabled") ? "disabled" : "") + ">";
                    }
                }
                /** {title:"",type:"",name:"",value:"",skin:"",filter:"",text:"",checked:""} */
                if (lable.type == 'switch') {
                    tempHtml = "<input type=\"checkbox\" name=\"" + lable.name + "\" value=\"" + lable.value + "\" lay-skin=\"switch\" lay-filter=\"" + lable.filter + "\" lay-text=\"" + lable.text + "\" checked>";
                }
                /** {title:"",type:"",name:"",placeholder:""} */
                if (lable.type == 'textarea') {
                    tempHtml = "<textarea name=\"" + lable.name + "\" placeholder=\"" + lable.placeholder + "\" class=\"layui-textarea\"></textarea>";
                }
                if (lable.type != 'hidden' && lable.type != 'text-pro' && tempHtml.length > 0) {
                    tempHtml = appendHtml(lable.title, tempHtml);
                }
                html += tempHtml;
            }
            return html + "</form></div>";
        },
        selecttree: function ({localtable, where}, {elem, url, title}) {
            apiRequest({
                url: url,
                params: {username: appConfig.userName}
            }).then(function (e) {
                if (e.code == 200) {
                    let data = dynamicform.formatdata(e.data, title);
                    tree.render({
                        elem: "#" + elem + "-tree", //指定元素
                        data: data,
                        click: function (node) { //点击节点回调
                            var othis = $($(this)[0].elem).parents(".layui-form-select");
                            othis.removeClass("layui-form-selected").find(".layui-select-title span").html(node.data.title).end().find("input:hidden[name='" + elem + "']").val(node.data.id);
                            localtable.options.where[where] = node.data.id;
                            localtable.reload();
                        }
                    });
                    $("." + elem).on("click", ".layui-select-title", function (e) {
                        $(".layui-form-select").not($(this).parents(".layui-form-select")).removeClass("layui-form-selected");
                        $(this).parents("." + elem).toggleClass("layui-form-selected");
                        layui.stope(e);
                    }).on("click", "dl i", function (e) {
                        layui.stope(e);
                    });
                } else {
                    layer.msg(e.description, {icon: 2, offset: '10px'})
                }
            })
        },
        formatdata: function (data, title) {
            return data.filter(father => {
                father.title = father[title];
                let branchArr = data.filter(child => father.id === child.parentid);
                branchArr.length > 0 ? (father.children = branchArr) : "";
                return father.parentid == "0"; // 如果第一层不是parentId=0，请自行修改
            });
        },
        renderCustomComp: function (lab) {
            for (let i in lab) {
                if (lab[i].type == 'date') {
                    laydate.render({
                        elem: `#${lab[i].name}`,
                        value: lab[i].value
                    });
                }
                if (lab[i].type == 'checkgroup') {
                    let selectPlusVal = selectPlus.render({
                        el: `#${lab[i].name}`,
                        data: lab[i].data,
                        valueSeparator: ' / ',
                        values: lab[i].value.split(',')
                    })
                }
                if (lab[i].type == 'treeuser') {
                    treeSelect.render({
                        elem: `#${lab[i].name}`,
                        data: '/usermanager',
                        type: 'post',
                        where: {username: appConfig.userName},
                        placeholder: '选择人员',
                        search: true,
                        tree: true,
                        click: function (d) {
                            $('#' + d.treeId).find('input').val(d.selectVal)
                            $(`#${lab[i].name}`).val(d.selectVal)
                        },
                        success: function () {
                        }
                    });
                }
                if (lab[i].type == 'treedanwei') {
                    treeSelect.render({
                        elem: `#${lab[i].name}`,
                        list: EnvConfig.sys_dicts.xzq,
                        placeholder: '选择单位',
                        search: true,
                        selectType: 'radio',
                        click: function (d) {
                            $(`#${lab[i].name}`).val(d.selectVal)
                        },
                        success: function () {
                        }
                    });
                }
            }
            element.init();
        },

        openwind: function (formparam, lables, rowdata, task) {
            let row = rowdata != null && rowdata != undefined && rowdata != "" ? JSON.parse(rowdata) : null;
            if (formparam.type == "delete") {
                layer.msg('确定删除此项吗？', {
                    time: 20000, //20s后自动关闭
                    btn: ['确定', '取消'],
                    yes: function (index) {
                        apiRequestCru({url: formparam.url[formparam.type], params: row}).then(function (e) {
                            if (e.code == 200) {
                                layer.msg("删除成功", {icon: 1, offset: '10px'});
                                if (task) task(formparam, row)
                                formparam.table.reload();
                            } else {
                                layer.msg(e.description, {icon: 2, offset: '10px'})
                            }
                            layer.close(index);
                        }).catch(function (e) {
                            layer.msg(e, {icon: 2, offset: '10px'})
                        })
                    }
                });
                return;
            }
            layer.open({
                type: 1,
                title: false,
                closeBtn: false,
                area: '600px',
                shade: 0,
                id: formparam.filter + '-lay', //设定一个id，防止重复弹出
                btn: ['确认', '取消'],
                btnAlign: 'c',
                moveType: 0, //拖拽模式，0或者1
                content: dynamicform.render(formparam, lables),
                success: function () {
                    form.render()
                    dynamicform.renderCustomComp(lables)
                    if (formparam.tabletype == "tree" && formparam.type == "insert") {
                        let temprow = {};
                        temprow.parentid = row == null ? "0" : row.id;
                        form.val(formparam.filter + '-example', temprow);
                    }
                    if (formparam.type == "update") {
                        row.state && row.state == 0 ? row.state = '' : row.state = 'on'
                        form.val(formparam.filter + '-example', row);
                    }
                },
                yes: function (index) {
                    let formdata = form.val(formparam.filter + '-example');
                    for (let key in formdata) {
                        let verify = $("[name='" + key + "']").attr("lay-verify");
                        if (verify != '' && verify != undefined) {
                            let title = $("[name='" + key + "']").parent().parent().children(":first").text();
                            let flag = validation.init(title, verify, formdata[key]);
                            if (!flag) {
                                $("[name='" + key + "']").css("border", "2px solid red");
                                $("[name='" + key + "']").focus(function () {
                                    $("[name='" + key + "']").css("border", "0");
                                });
                                return;
                            }
                        }
                    }

                    let dictionary = function (type) {
                        return type == "insert" ? "添加" : (type == "update" ? "更新" : "设置");
                    }
                    if (formdata.parentid == "0") {
                        if (formparam.injection != "") {
                            let injection = formparam.injection.split(",")
                            for (let i in injection) {
                                let param = $("input[name='" + injection[i] + "']").val();
                                formdata[injection[i]] = param;
                            }
                        }
                    }
                    apiRequestCru({url: formparam.url[formparam.type], params: formdata}).then(function (e) {
                        if (e.code == 200) {
                            layer.msg(dictionary(formparam.type) + "成功", {icon: 1, offset: '10px'})
                            if (task) task(formparam, row)
                            formparam.table.reload();
                        } else {
                            layer.msg(e.description, {icon: 2, offset: '10px'})
                        }
                        layer.close(index);
                    })
                }
            });
        }
    };
    exports('dynamicform', dynamicform);
});